<template>
  <div ref="line" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from 'echarts/core'
import { GridComponent } from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { debounce } from 'lodash'
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import 'echarts/theme/macarons'

echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition])

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  autoResize: {
    type: Boolean,
    default: true
  },
  chartData: {
    type: Object
  }
})

let chart = null
const line = ref(null)

const __resizeHandler = debounce(() => {
  if (chart) {
    chart.resize()
  }
}, 100)

onMounted(() => {
  initChart()

  if (props.autoResize) window.addEventListener('resize', __resizeHandler)

  const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
  sidebarElm.addEventListener('transitionend', __resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  if (props.autoResize) window.removeEventListener('resize', __resizeHandler)

  const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
  sidebarElm.removeEventListener('transitionend', __resizeHandler)
  chart.dispose()
  chart = null
})

watch(
  () => props.chartData,
  val => {
    setOptions(val)
  }
)

function initChart() {
  chart = echarts.init(line.value, 'macarons')
  setOptions(props.chartData)
}

function setOptions({ expectedData } = {}) {
  chart.setOption({
    xAxis: {
      data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    grid: {
      left: 10,
      right: 30,
      bottom: 20,
      top: 30,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: '试题数量',
        itemStyle: {
          color: '#3888fa',
          lineStyle: {
            color: '#3888fa',
            width: 2
          }
        },
        smooth: true,
        type: 'line',
        data: expectedData,
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      }
    ]
  })
}
</script>
